#include "debug.hpp"
#include "utils.hpp"
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sstream>
#include <iostream>
#include <stdexcept>

namespace icecode {

  Debug::Debug(std::string fname)
  {
    std::string f_name = icecode::utils::normalizePath(fname);
    log = ::open(f_name.c_str(), O_CREAT | O_WRONLY, S_IRUSR | S_IRGRP | S_IROTH | S_IWUSR);
    
    if(log >= 0) //Valid descriptor
      {
	rawMessage("Log session initialized.");
      }
    else throw std::runtime_error("Unable to open log file");
  }
  
  Debug::~Debug()
  {
    ::close(log);
    log = -1;
  }
  
  void Debug::rawMessage(std::string s, bool err) const throw()
  {
    ::time_t tim;
    register struct ::tm* t;
    std::stringstream ss;
    static std::string msg;
    
    ::time(&tim);
    t = ::gmtime(&tim);
    ss << '(' << t->tm_hour << ':' << t->tm_min << ':' << t->tm_sec << ") - " << s << std::endl;
    msg = ss.str();
    
    if(err)
      std::cerr << msg;
    else
      std::cout << msg;
    
    ::write(log, msg.c_str(), msg.size());
  }
  
  void Debug::msg(std::string s) throw()
  {
    std::string msg = "Message: ";
    msg.append(s);
    rawMessage(msg);
  }
  
  void Debug::error(std::string s) throw()
  {
    std::string msg = "Error: ";
    msg.append(s);
    rawMessage(msg, true);
  }
  
  void Debug::warning(std::string s) throw()
  {
    std::string msg = "Warning: ";
    msg.append(s);
    rawMessage(msg);
  }
}
